package com.snb.play.dwebtoon;

import java.io.File;
import java.math.BigInteger;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;

import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.StatFs;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.snb.play.dwebtoon.data.DTO_EpisodeImage;
import com.snb.play.dwebtoon.data.DTO_Result;
import com.snb.play.dwebtoon.data.DTO_WebToon;
import com.snb.play.dwebtoon.util.DBProvider;
import com.snb.play.dwebtoon.util.DownloadService;
import com.snb.play.dwebtoon.util.DownloadService.GINFO_STATUS;
import com.snb.play.dwebtoon.util.DownloadService.WEBTOON_SELECT_TYPE;
import com.snb.play.dwebtoon.util.ImageDownloader;
import com.snb.play.dwebtoon.util.Logger;
import com.snb.play.dwebtoon.util.SharedData;

public class WebToonListActivity extends BaseActivity implements OnMenuItemClickListener, OnTouchListener {
	private class WebToonListAdapter extends ArrayAdapter<DTO_WebToon> {

		private class ViewWrapper {
			private TextView mAdult;
			private TextView mAvr_Scr;
			private View mBase;
			private TextView mFinished;
			private TextView mLoading;
			public ImageView mThumb;
			private TextView mTitle;
			private ImageView mWait;
			private TextView mWriter;

			public ViewWrapper(View base) {
				mBase = base;
				if (mAvr_Scr == null) {
					mAvr_Scr = (TextView) mBase.findViewById(R.id.avr_scr);
				}

				if (mLoading == null) {
					mLoading = (TextView) mBase.findViewById(R.id.down_loading);
				}

				if (mWait == null) {
					mWait = (ImageView) mBase.findViewById(R.id.wait);
				}
				if (mAdult == null) {
					mAdult = (TextView) mBase.findViewById(R.id.tv_adult);
				}
				if (mFinished == null) {
					mFinished = (TextView) mBase.findViewById(R.id.tv_finished);
				}

				if (mThumb == null) {
					mThumb = (ImageView) mBase.findViewById(R.id.thumb);
				}

				if (mTitle == null) {
					mTitle = (TextView) mBase.findViewById(R.id.title);
					mTitle.setSelected(true);
				}
				if (mWriter == null) {
					mWriter = (TextView) mBase.findViewById(R.id.writer);
					mWriter.setSelected(true);
				}
			}

		}

		public WebToonListAdapter(Context context, ArrayList<DTO_WebToon> aLis) {
			super(context, R.layout.info_item, aLis);
			// mList = aLis;
		}

		@Override
		public void add(DTO_WebToon object) {
			super.add(object);
		}

		@Override
		public void addAll(Collection<? extends DTO_WebToon> collection) {
			super.addAll(collection);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			View row = convertView;

			ViewWrapper wrapper = null;

			if (row == null) {
				row = getLayoutInflater().inflate(R.layout.info_item, null);
				wrapper = new ViewWrapper(row);
				row.setTag(wrapper);
			} else {
				wrapper = (ViewWrapper) row.getTag();
			}

			final DTO_WebToon info = getItem(position);
			info.printMembers();
			if (info.getFinishYn().equalsIgnoreCase("y")) {
				wrapper.mFinished.setText("완");
				wrapper.mFinished.setVisibility(View.VISIBLE);
			} else {
				wrapper.mFinished.setVisibility(View.INVISIBLE);
			}

			boolean isAdult = false;
			if (info.getGenres().indexOf("성인") > -1)
				isAdult = true;

			if (isAdult) {
				wrapper.mAdult.setText("19");
				wrapper.mAdult.setVisibility(View.VISIBLE);
			} else {
				wrapper.mAdult.setVisibility(View.INVISIBLE);
			}

			wrapper.mTitle.setText(info.getTitle());
			// Logger.m(TAG, info.getTitle());
			wrapper.mTitle.setTypeface(Typeface.MONOSPACE, Typeface.BOLD);
			if (info.savedYn.equalsIgnoreCase("Y") || isSavedToon(info.id)) {
				wrapper.mTitle.setTextColor(0xFFFFFFFF);
				if (info.savedYn.equalsIgnoreCase("N")) {
					info.savedYn = "Y";
					DBProvider.getInstance().updateObjById(info);
				}
			} else {
				wrapper.mTitle.setTextColor(0xFFAAAAFF);
				if (info.savedYn.equalsIgnoreCase("Y")) {
					info.savedYn = "N";
					DBProvider.getInstance().updateObjById(info);
				}
			}

			wrapper.mTitle.setSelected(true);
			String lString = "";
			lString += "그림:" + info.getPicture_artists() + "\n글:" + info.getWrite_artists();

			// wrapper.mTitle.setTextSize((int) (mBaseFontSize * 0.9));
			wrapper.mWriter.setText(lString);
			// wrapper.mWriter.setTextSize((int) (mBaseFontSize * 0.8));
			wrapper.mWriter.setTypeface(Typeface.MONOSPACE, Typeface.ITALIC);
			if (info.getAverageScore().length() > 3)
				wrapper.mAvr_Scr.setText(info.getAverageScore().substring(0, 3));
			else
				wrapper.mAvr_Scr.setText(info.getAverageScore());
			lString = "";
			if (info.getThumbnailImage() != null && info.getThumbnailImage().length() > 3) {
				downloader.download(info.getThumbnailImage(), wrapper.mThumb, ContentListActivity.makeFileName(info.getThumbnailImage()));
			} else if (info.thumbnailImage2 != null && info.getThumbnailImage2().length() > 3) {
				downloader.download(info.getThumbnailImage2(), wrapper.mThumb, ContentListActivity.makeFileName(info.getThumbnailImage2()));
			}

			final int idx = position;
			if (gBinderManager.getService().haveToonLoaderTsk(info.getNickname())) {
				wrapper.mLoading.setVisibility(View.VISIBLE);
				wrapper.mWait.setVisibility(View.VISIBLE);
				wrapper.mWait.setAlpha(0.6f);
				wrapper.mWait.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rounding));
				wrapper.mLoading.setText("다운 로드 중...");
				row.setOnClickListener(null);
			} else {
				wrapper.mLoading.setVisibility(View.GONE);
				wrapper.mWait.setVisibility(View.GONE);
				if (wrapper.mWait.getAnimation() != null)
					wrapper.mWait.getAnimation().cancel();
				wrapper.mWait.setAnimation(null);
				wrapper.mLoading.setText("");
				row.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						lastSelectedItem = idx;
						CurrToon = getItem(idx);
						SharedData sharedData = new SharedData();

						sharedData.mMainId = getItem(idx).getId();
						sharedData.mMainNickName = getItem(idx).getNickname();
						sharedData.mToonName = getItem(idx).getTitle();
						startActivity(new Intent(WebToonListActivity.this, ContentListActivity.class).putExtra(ContentListActivity.TOONNAME,
								sharedData));
						overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
						// DownloadService.save_GInfo(getApplicationContext());
					}
				});
			}
			return row;
		}

		private boolean isSavedItem(String aMain_Id) {
			DTO_EpisodeImage lImg = new DTO_EpisodeImage();
			lImg.main_id = aMain_Id;
			return DBProvider.getInstance().getSelectObjTotalSize(lImg) > 0;
		}

		private boolean isSavedToon(String aId) {
			boolean returnV = false;
			returnV = isSavedItem(aId);
			return returnV;
		}

	}

	public static DTO_WebToon CurrToon = null;
	public static Context gCtx;
	public static int LastFilter = -1;
	public static int lastSelectedItem = -1;
	public static String MODE = "VIEW";
	public static int mRv;

	private final static Comparator<DTO_WebToon> myComparator = new Comparator<DTO_WebToon>() {

		private final Collator collator = Collator.getInstance();

		@Override
		public int compare(DTO_WebToon object1, DTO_WebToon object2) {

			if (LastFilter == 1)
				return collator.compare(object1.getTitle(), object2.getTitle());
			else if (LastFilter == 2)
				return collator.compare(String.valueOf(object1.getPicture_artists()), String.valueOf(object2.getPicture_artists()));
			else if (LastFilter == 10) {
				return collator.compare(object2.getAverageScore(), object1.getAverageScore());
			} else {
				return collator.compare(object1.getLastTouch(), object2.getLastTouch());
			}
		}
	};

	public static String TAG = WebToonListActivity.class.getSimpleName();

	public static long getAvailableSize(File mntdir) {
		return 0L;
	}

	public static Context getCtx() {
		return gCtx;
	}

	public static File[] getMntAvailableDirs() {
		return null;
	}

	public static long getTotalSize(File mntdir) {
		return 0L;
	}

	public static boolean isAvailableDir(File dir) {
		return false;
	}

	public ImageDownloader downloader = new ImageDownloader();

	private DTO_WebToon lDto_WebToon = null;
	private int lMinScore = 0;
	private DownloadService.WEBTOON_SELECT_TYPE lSelect_TYPE = WEBTOON_SELECT_TYPE.TOON_NONE;
	private WebToonListAdapter mAdapter;

	// float mBaseFontSize = 20;

	public EditText mSearchBox;

	public TextView mSize_noti;

	private Thread mTh;

	private int mTotalCount = 0;

	private GridView mView;

	public int mWidth = -1;

	int PageNum;

	public void diplayCurrentInfo() {
		try {
			gBinderManager.getService();
			mSize_noti.setText("현재 검색 결과 총: " + gBinderManager.getService().getCurrentGInfoSize() + "  | 현재 연재/완결 총: "
					+ gBinderManager.getService().getGInfoSize() + "\n사용중인 웹툰 저장 용량 : "
					+ FormatSize(FileUtils.sizeOfDirectoryAsBigInteger(new File(getExternalCacheDir().getParent()))));
//					+ FormatSize(gBinderManager.getService().getFullDirSize(getApplicationContext())));
		} catch (Exception e) {

		}
	}

	public String Direct(String name) {
		char b = name.trim().charAt(0);
		String[] chosung = { "ㄱ", "ㄱ", "ㄴ", "ㄷ", "ㄷ", "ㄹ", "ㅁ", "ㅂ", "ㅂ", "ㅅ", "ㅅ", "ㅇ", "ㅈ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ" };
		int first = (b - 44032) / (21 * 28);
		if (first <= 18 && first >= 0)
			return chosung[first];
		else
			return "";
	}

	private String FormatSize(BigInteger size) {
		String suffix = "Byte";
		Logger.d(TAG, "full size == " + size + suffix);
		BigInteger l1024 = BigInteger.valueOf(1024);
		if (size.compareTo(l1024) != -1) {
			suffix = "KB";
			size = size.divide(l1024);
			Logger.d(TAG, "full size == " + size + suffix);
			if (size.compareTo(l1024) != -1) {
				suffix = "MB";
				size = size.divide(l1024);
				Logger.d(TAG, "full size == " + size + suffix);
				if (size.compareTo(l1024) != -1) {
					suffix = "GB";
					size = size.divide(l1024);
					Logger.d(TAG, "full size == " + size + suffix);
				}
			}

		}

		StringBuilder resultBuffer = new StringBuilder(size.toString());

		int commaOffset = resultBuffer.length() - 3;
		while (commaOffset > 0) {
			resultBuffer.insert(commaOffset, ',');
			commaOffset -= 3;
		}

		if (suffix != null) {
			resultBuffer.append(suffix);
		}

		return resultBuffer.toString();
	}

	public long getSDSize(File file) {
		StatFs stat = new StatFs(file.getAbsolutePath() + "/");
		long blockSize = stat.getBlockSize();
		long totalBlocks = stat.getBlockCount();
		return totalBlocks * blockSize;
	}

	private String makeEngWeek(String week) {
		if (week.equalsIgnoreCase("월"))
			return "mon";
		else if (week.equalsIgnoreCase("화"))
			return "tue";
		else if (week.equalsIgnoreCase("수"))
			return "wed";
		else if (week.equalsIgnoreCase("목"))
			return "thu";
		else if (week.equalsIgnoreCase("금"))
			return "fri";
		else if (week.equalsIgnoreCase("토"))
			return "sat";
		else
			return "sun";
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		AlertDialog.Builder lDB = new AlertDialog.Builder(WebToonListActivity.this);
		lDB.setMessage("종료 할꺼??\n만화 더 안봐??");
		lDB.setTitle("앱 끌꺼임?");
		lDB.setIcon(R.drawable.snb_comic_icon);
		lDB.setPositiveButton("확인", new AlertDialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				WebToonListActivity.this.finish();
				dialog.dismiss();
			}
		});
		lDB.setNegativeButton("취소", new AlertDialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		lDB.create().show();
	}

	RelativeLayout main_seach;
	RadioGroup main_sub_rg_day;
	RadioGroup main_sub_rg_score;
	LinearLayout main_lin;
	private GestureDetector mGestureDetector;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list);

		main_lin = (LinearLayout) findViewById(R.id.main_lin);
		main_seach = (RelativeLayout) findViewById(R.id.main_seach);
		main_sub_rg_day = (RadioGroup) findViewById(R.id.main_sub_rg_day);
		main_sub_rg_score = (RadioGroup) findViewById(R.id.main_sub_rg_score);

		mSimpleGestureListener = new SimpleGestureListener();
		mGestureDetector = new GestureDetector(this, mSimpleGestureListener);

		main_lin.setOnTouchListener(this);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub

		if (v.equals(main_lin)) {
//			Log.d("TEST", "onTouch event ==> " + event.toString() + " event.getAction() ->" + event.getAction());
//			return mGestureDetector.onTouchEvent(event);
		}
		return false;
	}

	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			Log.d("TEST", "LastGs ==" + mGs);
			return false;
		} else
			return mGestureDetector.onTouchEvent(event);
	};

	SimpleGestureListener mSimpleGestureListener;

	private final class SimpleGestureListener extends GestureDetector.SimpleOnGestureListener {

		@Override
		public boolean onDoubleTap(MotionEvent e) {
			Log.d("TEST", "onDoubleTap e ==> " + e.toString());
			return super.onDoubleTap(e);
		}

		@Override
		public boolean onDoubleTapEvent(MotionEvent e) {
			Log.d("TEST", "onDoubleTapEvent e ==> " + e.toString());
			return super.onDoubleTapEvent(e);
		}

		@Override
		public boolean onDown(MotionEvent e) {
			Log.d("TEST", "onDown e ==> " + e.toString());
			return super.onDown(e);
		}

		@Override
		public void onLongPress(MotionEvent e) {
			Log.d("TEST", "onLongPress e ==> " + e.toString());
			super.onLongPress(e);
		}

		@Override
		public void onShowPress(MotionEvent e) {
			Log.d("TEST", "onShowPress e ==> " + e.toString());
			super.onShowPress(e);
		}

		@Override
		public boolean onSingleTapConfirmed(MotionEvent e) {
			Log.d("TEST", "onSingleTapConfirmed e ==> " + e.toString());
			return super.onSingleTapConfirmed(e);
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			// TODO Auto-generated method stub
			Log.d("TEST", "onSingleTapUp e ==> " + e.toString());
			return super.onSingleTapUp(e);
		}

		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//			Log.d("TEST", "!!!!!\nonFling \n e1 ==> " + e1.toString() + "\n e2 ==>" + e2.toString() + "\n velocityX == " + velocityX + " \n velocityY"
//					+ velocityY);
			mGs = GsType.STOP_G;
			if (Math.abs(e1.getX() - e2.getX()) < 20) {
				if (e1.getY() > e2.getY() && Math.abs(e1.getY() - e2.getY()) > 20) {
					Log.d("TEST", "onFling 올림");
					mGs = GsType.UP_G;
				} else if (e1.getY() < e2.getY() && Math.abs(e1.getY() - e2.getY()) > 20) {
					Log.d("TEST", "onFling 내림");
					mGs = GsType.DOWN_G;
				} else {
					Log.d("TEST", "onFling 그대로 세로");
				}
			} else {
				Log.d("TEST", "onFling 그대로 가로");
			}
			return super.onFling(e1, e2, velocityX, velocityY);
		}

		@Override
		public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
//			Log.d("TEST", "onScroll e1 ==> " + e1.toString() + " e2 ==>" + e2.toString());
			mGs = GsType.STOP_G;
			if (Math.abs(e1.getX() - e2.getX()) < 20) {
				if (e1.getY() > e2.getY() && Math.abs(e1.getY() - e2.getY()) > 20) {
					Log.d("TEST", "onScroll 올림");
					mGs = GsType.UP_G;
				} else if (e1.getY() < e2.getY() && Math.abs(e1.getY() - e2.getY()) > 20) {
					Log.d("TEST", "onScroll 내림");
					mGs = GsType.DOWN_G;
				} else {
					Log.d("TEST", "onScroll 그대로 세로");
				}
			} else {
				Log.d("TEST", "onScroll 그대로 가로");
			}
			return super.onScroll(e1, e2, distanceX, distanceY);
		}
	}

	GsType mGs;

	private enum GsType {
		UP_G, DOWN_G, STOP_G
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "월").setOnMenuItemClickListener(this);
		menu.add(0, 0, 0, "화").setOnMenuItemClickListener(this);
		menu.add(0, 0, 0, "수").setOnMenuItemClickListener(this);
		menu.add(0, 0, 0, "목").setOnMenuItemClickListener(this);
		menu.add(0, 0, 0, "금").setOnMenuItemClickListener(this);
		menu.add(0, 0, 0, "토").setOnMenuItemClickListener(this);
		menu.add(0, 0, 0, "일").setOnMenuItemClickListener(this);
		menu.setQwertyMode(true);
		return true;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onMenuItemClick(MenuItem item) {
		mSearchBox.setVisibility(View.GONE);
		mSearchBox.setText("");
		lSelect_TYPE = WEBTOON_SELECT_TYPE.TOON_BY_DAY;

		lDto_WebToon = new DTO_WebToon();
		Logger.d(TAG, makeEngWeek(item.getTitle().toString().trim()));
		lDto_WebToon.webtoonWeeks = makeEngWeek(item.getTitle().toString().trim());
		lDto_WebToon.savedYn = "N";
		new Handler().post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Collections.sort(gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore), myComparator);
				Collections.reverse(gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore));
				mView.setAdapter(new WebToonListAdapter(getApplicationContext(), gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon,
						lMinScore)));
				mView.invalidateViews();
				diplayCurrentInfo();
			}
		});

		return false;
	}

	public boolean onMenuItemClick(View view) {
		mSearchBox.setVisibility(View.GONE);
		mSearchBox.setText("");
		lSelect_TYPE = WEBTOON_SELECT_TYPE.TOON_BY_DAY;

		lDto_WebToon = new DTO_WebToon();
		Logger.d(TAG, makeEngWeek(((RadioButton) view).getText().toString().trim()));
		lDto_WebToon.webtoonWeeks = makeEngWeek(((RadioButton) view).getText().toString().trim());
		lDto_WebToon.savedYn = "N";

		Collections.sort(gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore), myComparator);
		Collections.reverse(gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore));
		mView.setAdapter(new WebToonListAdapter(getApplicationContext(), gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore)));
		mView.invalidateViews();
		diplayCurrentInfo();
		return false;
	}

	boolean isFirst = true;

	@Override
	protected void onResume() {
		super.onResume();
		gBinderManager.getService().mStatus = GINFO_STATUS.IDLE;
		mSize_noti = (TextView) findViewById(R.id.size_noti);

		mSearchBox = (EditText) findViewById(R.id.keyword);
		mSearchBox.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		mSearchBox.setImeActionLabel("검색", EditorInfo.IME_ACTION_SEARCH);
		if (isFirst) {
			mView = (GridView) findViewById(R.id.main_list);

			gBinderManager.getService().getGInfo(WEBTOON_SELECT_TYPE.TOON_ALL, new DTO_WebToon(), lMinScore);
			if (gBinderManager.getService().getGInfoSize() > 0) {
				mAdapter = new WebToonListAdapter(getApplicationContext(), gBinderManager.getService().getGInfo(WEBTOON_SELECT_TYPE.TOON_ALL,
						new DTO_WebToon(), lMinScore));
			} else {
				ArrayList<DTO_WebToon> ll = new ArrayList<DTO_WebToon>();
				mAdapter = new WebToonListAdapter(getApplicationContext(), ll);
			}
			mView.setNumColumns(3);
			mSearchBox.setOnEditorActionListener(new OnEditorActionListener() {

				@Override
				public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					if (actionId == EditorInfo.IME_ACTION_SEARCH) {
						ArrayList<DTO_WebToon> tmpArrayList = new ArrayList<DTO_WebToon>();

						for (DTO_WebToon lWebToon : gBinderManager.getService().getGInfo(WEBTOON_SELECT_TYPE.TOON_ALL, new DTO_WebToon(), lMinScore)) {
							if (LastFilter == 2) {
								if (lWebToon.getPicture_artists().trim().toUpperCase().indexOf(mSearchBox.getText().toString().trim().toUpperCase()) > -1
										|| lWebToon.getWrite_artists().trim().toUpperCase()
												.indexOf(mSearchBox.getText().toString().trim().toUpperCase()) > -1)
									tmpArrayList.add(lWebToon);
							} else {
								if (lWebToon.getTitle().trim().toUpperCase().indexOf(mSearchBox.getText().toString().trim().toUpperCase()) > -1)
									tmpArrayList.add(lWebToon);
							}
						}
						mView.setAdapter(new WebToonListAdapter(getApplicationContext(), tmpArrayList));
						mView.invalidateViews();

						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(mSearchBox.getWindowToken(), 0);

						return true;
					}
					return false;
				}
			});

			if (mTotalCount == 0 || gBinderManager.getService().getGInfoSize() < mTotalCount) {
				Logger.d(TAG, "updateWebToonList 호출한다. gInfo == " + gBinderManager.getService().getGInfoSize() + " totalCnt ==  " + mTotalCount);
				PageNum = 1;
				updateWebToonList(PageNum);
			} else {
			}

			isFirst = false;
			if (mRv == -1 || findViewById(mRv) == null)
				try {
					((RadioButton) findViewById(R.id.rb_save)).setChecked(true);
					xmlOnClick(((RadioButton) findViewById(R.id.rb_save)));

				} catch (Exception e) {

				}
			else {
				((RadioButton) findViewById(mRv)).setChecked(true);
				xmlOnClick(findViewById(mRv));
			}
		}
	}

	@Override
	protected void onStart() {
		super.onStart();

		DBProvider.initInstance(getApplicationContext());
		downloader.clearCache();

		gCtx = getApplicationContext();

		// if (mTotalCount <= 0)
		if (getRest() != null)
			mTotalCount = getRest().getDaumWebToonCount();

	}

	public void updateWebToonList(final int aPageNum) {
		if (gProgressDialog == null) {
			gProgressDialog = new ProgressDialog(this);
			gProgressDialog.setTitle("데이터 로딩중...");
			gProgressDialog.setIcon(R.drawable.snb_comic_icon);
			gProgressDialog.setMessage("기다려~ \n웹툰 정보를  채워주는 중임\n첨엔 시간 걸려\n귀찮아서 끄면 담에 다시한다-_-;;\n담부턴 웹툰 추가될때만\n추가로 채워줄꼬양");
			gProgressDialog.setCancelable(false);
			gProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			gProgressDialog.setMax(mTotalCount);
			gProgressDialog.setProgress(gBinderManager.getService().getGInfoSize() > 0 ? gBinderManager.getService().getGInfoSize() : 0);

		}

		if (!gProgressDialog.isShowing()) {
			gProgressDialog.show();
			gProgressDialog.setProgress(gBinderManager.getService().getGInfoSize() > 0 ? gBinderManager.getService().getGInfoSize() : 0);
			gProgressDialog.setMax(mTotalCount);
		}
		gBinderManager.getService().mStatus = GINFO_STATUS.SAVE;

		mTh = new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					JSONObject full = null;
					// DBProvider.getInstance().begin();
					gProgressDialog.setMax(mTotalCount);
					gProgressDialog.setProgress(gBinderManager.getService().getGInfoSize() > 0 ? gBinderManager.getService().getGInfoSize() : 0);
					try {
						full = getRest().getDaumWebToon(aPageNum);
						Logger.d(TAG, " full 시작");
					} catch (Exception e1) {
						e1.printStackTrace();
					}
					JSONObject page = null;
					DTO_Result lDto_Result = null;
					JSONArray webtoonList = null;
					if (full != null) {
						page = full.getJSONObject("page");
						lDto_Result = new DTO_Result(full.getJSONObject("result"));
					}

					if (lDto_Result != null && (lDto_Result.status.equalsIgnoreCase("200") || lDto_Result.message.length() < 1) && full != null
							&& page != null) {
						// IntroActivity.getGInfo();

						if (mTotalCount == 0) {
							mTotalCount = Integer.parseInt(page.getString("totalItemCount"));
						}

						if (mTotalCount > 0 && mTotalCount == gBinderManager.getService().getGInfoSize()) {
							gBinderManager.getService().mStatus = GINFO_STATUS.IDLE;
							if (gProgressDialog != null && gProgressDialog.isShowing()) {
								gProgressDialog.dismiss();
							}
							mTh.interrupt();
						} else {

							webtoonList = full.getJSONObject("data").getJSONArray("webtoonList");
							if (webtoonList != null && webtoonList.length() > 0) {
								for (int i = 0; i < webtoonList.length(); i++) {
									JSONObject l_Json_WebToonInfo = webtoonList.getJSONObject(i);
									DTO_WebToon lInfo = new DTO_WebToon(l_Json_WebToonInfo);
									if (lInfo.getThumbnailImage() != null && lInfo.getThumbnailImage().length() > 0) {
										lInfo.setThumbnailImage(lInfo.thumbnailImage);
									} else if (lInfo.getThumbnailImage2() != null && lInfo.getThumbnailImage2().length() > 0) {
										lInfo.setThumbnailImage2(lInfo.thumbnailImage2);
									}
									lInfo.insertObjToDB();
									gProgressDialog.setMax(mTotalCount);
									gProgressDialog.setProgress(gBinderManager.getService().getGInfoSize() > 0 ? gBinderManager.getService()
											.getGInfoSize() : 0);
								}
							}
						}
					}
					Logger.d(TAG, "check PageNum == " + PageNum + " mTotalCount == " + mTotalCount + " MainActivity.gInfo.size() == "
							+ gBinderManager.getService().getGInfoSize());
					gProgressDialog.setMax(mTotalCount);
					gProgressDialog.setProgress(gBinderManager.getService().getGInfoSize() > 0 ? gBinderManager.getService().getGInfoSize() : 0);
					if (mTotalCount > gBinderManager.getService().getGInfoSize()) {
						DBProvider.getInstance().close();
						Logger.d(TAG, "end PageNum == " + PageNum);
						PageNum++;
						updateWebToonList(PageNum);
					} else {
						if (gProgressDialog != null && gProgressDialog.isShowing()) {
							gProgressDialog.dismiss();
						}
						gBinderManager.getService().mStatus = GINFO_STATUS.IDLE;
						mTh.interrupt();
					}

				} catch (JSONException e1) {
					e1.printStackTrace();
					gBinderManager.getService().mStatus = GINFO_STATUS.IDLE;
				}
			}
		}, TAG);

		mTh.start();
	}

	public void xmlOnClickScore(View v) {
		switch (v.getId()) {
			case R.id.sub_10_9:
				lMinScore = 9;
				break;
			case R.id.sub_9_8:
				lMinScore = 8;
				break;
			case R.id.sub_8_7:
				lMinScore = 7;
				break;
			case R.id.sub_7_5:
				lMinScore = 5;
				break;
			case R.id.sub_5_0:
				lMinScore = 0;
				break;
			default:
				break;
		}

		xmlOnClick(findViewById(R.id.rb_score));
	}

	int lSaveSortFilter;
	DownloadService.WEBTOON_SELECT_TYPE l_Select_TYPE;

	public void xmlOnClick(View v) {
		mRv = v.getId();

		if (gBinderManager.getService().getGInfoSize() < 1)
			return;

		main_seach.setVisibility(View.GONE);
		main_sub_rg_day.setVisibility(View.GONE);
		main_sub_rg_score.setVisibility(View.GONE);
		l_Select_TYPE = WEBTOON_SELECT_TYPE.TOON_ALL;
		lDto_WebToon = new DTO_WebToon();
		lSaveSortFilter = 0;
		mSearchBox.setVisibility(View.GONE);
		synchronized (gBinderManager) {

			switch (v.getId()) {
				case R.id.rb_title: {
					lSaveSortFilter = 1;
					l_Select_TYPE = WEBTOON_SELECT_TYPE.TOON_BY_TITLE;
					mSearchBox.setVisibility(View.VISIBLE);
					lDto_WebToon.title = mSearchBox.getText().toString();
					lDto_WebToon.savedYn = "N";
					main_seach.setVisibility(View.VISIBLE);
					lMinScore = 0;
					break;
				}
				case R.id.rb_writer: {
					lSaveSortFilter = 2;
					l_Select_TYPE = WEBTOON_SELECT_TYPE.TOON_BY_ARTIST;
					mSearchBox.setVisibility(View.VISIBLE);
					lDto_WebToon.picture_artists = mSearchBox.getText().toString();
					lDto_WebToon.write_artists = mSearchBox.getText().toString();
					lDto_WebToon.savedYn = "N";
					main_seach.setVisibility(View.VISIBLE);
					lMinScore = 0;
					break;
				}
				case R.id.rb_fin: {
					l_Select_TYPE = WEBTOON_SELECT_TYPE.TOON_FINISHED;
					lSaveSortFilter = 3;
					mSearchBox.setText("");
					lDto_WebToon.finishYn = "Y";
					lDto_WebToon.savedYn = "N";
					main_sub_rg_day.setVisibility(View.VISIBLE);
					lMinScore = 0;
					break;
				}
				case R.id.rb_save: {
					l_Select_TYPE = WEBTOON_SELECT_TYPE.TOON_SAVED;
					lSaveSortFilter = 0;
					lDto_WebToon.savedYn = "Y";
					mSearchBox.setText("");
					lMinScore = 0;
				}
					break;
				case R.id.rb_score: {
					l_Select_TYPE = WEBTOON_SELECT_TYPE.TOON_ALL;
					lSaveSortFilter = 10;
					lDto_WebToon.savedYn = "N";
					main_sub_rg_score.setVisibility(View.VISIBLE);

				}
					break;
				default:
					break;
			}

			LastFilter = 0;
			if (gBinderManager.getService().getGInfoSize() > 0) {
				new Handler().post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Collections.sort(gBinderManager.getService().getGInfo(l_Select_TYPE, lDto_WebToon, lMinScore), myComparator);
						Collections.reverse(gBinderManager.getService().getGInfo(l_Select_TYPE, lDto_WebToon, lMinScore));
						if (LastFilter != lSaveSortFilter) {
							LastFilter = lSaveSortFilter;
							Collections.sort(gBinderManager.getService().getGInfo(l_Select_TYPE, lDto_WebToon, lMinScore), myComparator);
						}
						mView.setAdapter(new WebToonListAdapter(getApplicationContext(), gBinderManager.getService().getGInfo(l_Select_TYPE,
								lDto_WebToon, lMinScore)));
						mView.invalidateViews();
						diplayCurrentInfo();
					}
				});

			}
		}
	}

	@Override
	protected void refresh(String aString) {
		Toast.makeText(this, aString + " 다운 완료!", Toast.LENGTH_LONG).show();
//			if (mView != null) {
		int lSaveSortFilter = LastFilter;
		LastFilter = 0;
		gBinderManager.getService().resetGInfofilter();
		if (gBinderManager.getService().getGInfoSize() > 0) {
			Collections.sort(gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore), myComparator);
			Collections.reverse(gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore));
			if (LastFilter != lSaveSortFilter) {
				LastFilter = lSaveSortFilter;
				Collections.sort(gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon, lMinScore), myComparator);
			}
			mView.setAdapter(new WebToonListAdapter(getApplicationContext(), gBinderManager.getService().getGInfo(lSelect_TYPE, lDto_WebToon,
					lMinScore)));
			mView.invalidateViews();
			diplayCurrentInfo();
		}
	}
}
